package app.tuwien.isi.tweetanalyser;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {

	static final Uri tweetUri = Uri.parse("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=");
	static final Uri userIdUri = Uri.parse("http://api.twitter.com/1/statuses/user_timeline.json?user_id=");
    static final Uri queryUri = Uri.parse("http://search.twitter.com/search.json?q=%23");
    static final String twitteruser = "&with_twitter_user_id=true";
    HttpClient client;
    ListView listView;
    Spinner spinnerSort;
    ArrayList<Tweet> tweets;
    
    @Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tweets);
        
        client = new DefaultHttpClient();
        
        spinnerSort = (Spinner) findViewById(R.id.spinnerSort);
        String sortString[] = {"sort by","time","retweets"};
        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, sortString);
        spinnerSort.setAdapter(spinnerArrayAdapter); 
    	
        spinnerSort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
			
			public void  onItemSelected(AdapterView<?> parent, View view, int position, long id){
				if(position != 0){
					sort(position);
					listView.invalidateViews();
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {				
			}
		});
    	
        listView = (ListView) findViewById(R.id.list);
        
        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
//                Tweet tweet = (Tweet) adapterView.getItemAtPosition(position);
//
//                Intent intent = new Intent(Intent.ACTION_VIEW);
//                intent.setData(Uri.parse(
//                    "http://twitter.com/#!/InsertEffect/status/" + 
//                    tweet.getId()
//                ));
//                startActivity(intent);
//            	
            	
            }
        });
        
        Button statisticButton = (Button) findViewById(R.id.button);
        
        statisticButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	Intent intent = new Intent (getApplicationContext(), StatisticActivity.class);
            	
            	if(tweets == null){
            		Log.e("TweetList","is null");
            	}else{
	            	intent.putParcelableArrayListExtra("tweets", tweets);  	
	            	startActivityForResult(intent, 1);
            	}
            }
        });
        
        Button mapButton = (Button) findViewById(R.id.buttonMaps);
        
        mapButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	Intent intent = new Intent (getApplicationContext(), LocationActivity.class);
            	
            	if(tweets == null){
            		Log.e("TweetList","is null");
            	}else{
	            	intent.putParcelableArrayListExtra("tweets", tweets);  	
	            	startActivityForResult(intent, 1);
            	}
            }
        });
        
        Intent intent = getIntent();
        
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            
            if(query.startsWith("@")){
            	loadTweets(Uri.parse(tweetUri + query.substring(1)));
            }else{
            	if(query.startsWith("#")){
            		//TODO Hashtag verarbeitung
            		loadQuery(Uri.parse(queryUri + query.substring(1) + twitteruser));
            	}else{
            		Toast toast = Toast.makeText(MainActivity.this, "'#Hashtag' or '@User'", Toast.LENGTH_SHORT);
            		toast.show();
            	}
            }
        }else{
        	if(intent.getStringExtra("query") != null){
        		String query = intent.getStringExtra("query");
                
                if(query.startsWith("@")){
                	loadTweets(Uri.parse(tweetUri + query.substring(1)));
                }else{
                	if(query.startsWith("#")){
                		loadQuery(Uri.parse(queryUri + query.substring(1) + twitteruser));
                	}else{
                		Toast toast = Toast.makeText(MainActivity.this, "'#Hashtag' or '@User'", Toast.LENGTH_SHORT);
                		toast.show();
                	}
                }
        	}else{
        		loadTweets(Uri.parse(tweetUri + "Philipp_Pos"));
        	}
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.searchview, menu);
        
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
        return true;
    }
    
    void loadTweets(Uri uri) {
        AsyncTask<Uri, Object, List<Tweet>> task = new TwitterTask();
        task.execute(uri);
    }
    
    void loadQuery(Uri uri) {
        AsyncTask<Uri, Object, List<Tweet>> task = new QueryTask();
        task.execute(uri);
    }
    
    private class TwitterTask extends AsyncTask<Uri, Object, List<Tweet>> {
    	
        public TwitterTask() {
		}
        
		@Override
		protected void onPostExecute(List<Tweet> result) {
			tweets = (ArrayList<Tweet>) result;
            listView.setAdapter(new TweetAdapter(MainActivity.this, result));
        }
		
		@Override
		protected List<Tweet> doInBackground(Uri... arg0) {
            try {

                HttpGet get = new HttpGet(arg0[0].toString());
                HttpResponse response = client.execute(get);
                String result = EntityUtils.toString(response.getEntity());

                JSONArray array = new JSONArray(result);
                ArrayList<Tweet> tweets = new ArrayList<Tweet>(array.length());

                for(int i=0; i < array.length(); i++) {
                    JSONObject object = array.getJSONObject(i);
                    
                    Tweet tweet = new Tweet(object,0);
                    tweets.add(tweet);
                }

                return tweets;
            } catch(Exception ex) {
                    throw new RuntimeException(ex);
            }
        }
    }
    
    private class QueryTask extends AsyncTask<Uri, Object, List<Tweet>> {
    	
        public QueryTask() {
		}
        
		@Override
		protected void onPostExecute(List<Tweet> result) {
			tweets = (ArrayList<Tweet>) result;
            listView.setAdapter(new TweetAdapter(MainActivity.this, result));
        }
		
        @Override
		protected ArrayList<Tweet> doInBackground(Uri... arg0) {
            try {
                HttpGet get = new HttpGet(arg0[0].toString());
                HttpResponse response = client.execute(get);
                ArrayList<Tweet> tempTweets = null;
                
                if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
	                String result = EntityUtils.toString(response.getEntity());
	                
	                JSONObject root = new JSONObject(result);
	                JSONArray array = root.getJSONArray("results");
	                tempTweets = new ArrayList<Tweet>(array.length());

	                for(int i=0; i < array.length(); i++) {
	                    JSONObject object = array.getJSONObject(i);
	                    
	                    Tweet tweet = new Tweet(object,1);
	                    tempTweets.add(tweet);
	                }
	                
                }
                //TODO
                for(int i=0; i<tempTweets.size();i++){
	                get = new HttpGet(userIdUri + String.valueOf(tempTweets.get(i).getUserID()));
	                response = client.execute(get);
	               
	                if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
		                String result = EntityUtils.toString(response.getEntity());

		                result = result.substring(result.indexOf("\"user\"")+6);
		                result = result.substring(result.indexOf("{")+1,result.indexOf("}"));
		                result = result.substring(result.indexOf("\"name\":\"")+8);
		                String userName = result.substring(0,result.indexOf("\""));
		                result = result.substring(result.indexOf("\"location\":\"")+12);
		                String userLocation;
		                if(result.substring(0,4).equals(null)){
		                	userLocation = ""; //TODO vielleicht auch nulll
		                }else{
		                	userLocation = result.substring(0,result.indexOf("\""));
		                }
		                result = result.substring(result.indexOf("\"followers_count\":")+18);
		                int followers = Integer.parseInt(result.substring(0,result.indexOf(",")));
		                result = result.substring(result.indexOf("\"lang\":\"")+8);
		                String language = result.substring(0,result.indexOf("\""));
		                result = result.substring(result.indexOf("\"profile_image_url_https\":\"") + 27);
		                String profileImage = result.substring(0,result.indexOf("\""));
		                for(int n=0; n<profileImage.length();n++){
		                	if(profileImage.indexOf("\\") != -1){
		                		profileImage = profileImage.substring(0, profileImage.indexOf("\\")) + profileImage.substring(profileImage.indexOf("\\")+1);
		                	}
		                }

		                tempTweets.get(i).addProperties(userName, profileImage, userLocation, language, followers);
	                }
                }
                
                return tempTweets;
            } catch(Exception ex) {
                    throw new RuntimeException(ex);
            }
        }
    }
   
    private void sort(int sortby){
    	Tweet temp = null;
    	for (int n=tweets.size(); n>1; n=n-1){
    		for (int i=0; i<n-1; i=i+1){
    			if (sortby == 1 && tweets.get(i+1).getDate().after(tweets.get(i).getDate())){
    				temp = tweets.get(i);
    				tweets.set(i, tweets.get(i+1));
    				tweets.set(i+1, temp);
    			}
    			if (sortby == 2 && tweets.get(i).getRetweetCount() < tweets.get(i+1).getRetweetCount()){
    				temp = tweets.get(i);
    				tweets.set(i, tweets.get(i+1));
    				tweets.set(i+1, temp);
    			}
    		}
    	}
    }
}
